<template>
  <van-field
    v-show="visible" 
    v-model.trim="value"
    :label="label" 
    :placeholder="placeholder"
    :readonly="readonly" 
    :required="required"
    :error="error"
    :error-message="errorMessage"
    :type="type"
    @focus="focus"
    @blur="blur"/>
</template>

<script>
import validateRules from "utils/validateRules"

export default {
  name: 'mb-field',
  data() {
    return {
      value: '',
      error: false,
      errorMessage: '',
      visible: true
    }
  },
  props: ["item","result"],
  computed: {
    label() {
      return this.item.caption || this.item.name
    },
    placeholder() {
      return this.item.readonly?"":"请输入" + (this.item.caption || this.item.name || '')
    },
    required() {
      return this.item.required
    },
    readonly() {
      return this.item.readonly
    },
    type() {
      if(this.item.xtype === "number") {
        return this.item.dataType === "int" ? "digit" : "number"
      } else if (this.item.xtype === "textarea") {
        return "textarea"
      }
      return "text"
    }
  },
  watch: {
    value: function(newVal) {
      let emitObj = {};
      emitObj[this.item.name] = newVal;
      this.$emit("formChange", this.item.name, emitObj, this.item)
    },
    result: function(newVal) {
      this.value = newVal
    }
  },
  methods: {
    focus() {
      this.error = false;
    },
    blur() {
      if(this.validate()) {
        this.error = false;
        this.errorMessage = '';
      }
    },
    validate() {
      // 隐藏跳过校验
      if(!this.visible) return true 
      if(this.item.required && !validateRules.required.func(this.value)) {
        this.error = true
        return false
      }
      if(this.item.checkType && this.value) {
        if(this.item.checkType === "maxLength") {
          if(!validateRules.maxLength.func(this.value, this.item.checkSize)) {
            this.errorMessage = this.item.alertText || validateRules.maxLength.alertText;
            return false
          }
        } else if(this.item.checkType === "custom") {
          if(!eval(this.item.checkExp).test(this.value)) {
            this.errorMessage = this.item.alertText || "";
            return false
          }
        } else {
          if(validateRules[this.item.checkType] && !validateRules[this.item.checkType]["regex"].test(this.value)) {
            this.errorMessage = this.item.alertText || validateRules[this.item.checkType]["alertText"];
            return false
          }
        }
      }
      return true
    }
  },
  mounted() {
    let emitObj = {};
    emitObj[this.item.name] = this.result;
    this.$emit("formChange", this.item.name, emitObj, this.item)
  }
}
</script>
